
import psycopg2.extras
import sys
from shapely.geometry import box
from shapely.wkt import dumps, loads
import gdal
from gdalconst import *
import os
import constant
import glob

def main(resx=0.117292465957718, resy=-0.117292465957718):
	con = None
	try:
		con = psycopg2.connect(host='192.168.3.4', database='fimo', user='rasdaman', password='rasdaman') 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		cur.execute("SELECT filename, path , date_part('year', aqstime) as year from satorglandcover")
		rows = cur.fetchall()
		
		lastyear = -1
		merge_command = ["","","","",""]
		for row in rows:
			year = int(row['year'])
			filename = row["filename"].strip()
			path = row["path"].strip()
			#path = path.replace("/home/phamha/", "/media/EXT/")
			path = os.path.join("/var/www/html/", path)
			inputfilename = os.path.join(path, filename)
			if year != lastyear:
				for index in range(1,6):
					if lastyear != -1:
						print( merge_command[index-1])
						os.system(merge_command[index-1])

					outputfile = os.path.join("/var/www/html/fimo/public/ReLandCover/{0}".format(year), "B{0}.tif".format(index))
					if not os.path.exists(os.path.dirname(outputfile)):
						os.makedirs(os.path.dirname(outputfile))
					merge_command[index-1] = "python gdal_merge.py -o {0} -ot Byte -n 0 -a_nodata 0".format(outputfile)
				lastyear = year

			for index in range(1,6):
				inputfile = 'HDF4_EOS:EOS_GRID:"'+inputfilename+'":MOD12Q1:Land_Cover_Type_{0}'.format(index)
				merge_command[index-1] += " " + inputfile
		
		for index in range(1,6):
			outputfile = os.path.join(path.replace("/var/www/html/fimo/public/SatOrgLandCover/", "/var/www/html/fimo/public/ReLandCover/"), filename + "_B{0}_10km.tif".format(index))
			if not os.path.exists(os.path.dirname(outputfile)):
				os.makedirs(os.path.dirname(outputfile))
			os.system(merge_command[index-1])
		
		# re_griding(inputfile, resx, resy, outputfile)

	except psycopg2.DatabaseError as e:
		print ('Error',e)  
		sys.exit(1)
	finally:
		if con:
			con.close()

def re_griding(inputfile, resx, resy, ouputfile):
	regrid_command = "gdalwarp -t_srs '+proj=longlat +datum=WGS84' -ot Byte -wt Byte -te 100.1 6.4 111.8 25.6 -tr {0} {1} -r mode -srcnodata 255 -dstnodata 255 -overwrite {2} {3}".format(resx, resy, inputfile, ouputfile)
	os.system(regrid_command)
def regrid_landcover():
	
	path ="/var/www/html/fimo/apom/Resample/SatResampLandCover/*/*.tif"
	for infile in glob.iglob(path):
		outfile3=infile.replace(".tif","_3km.tif")
		outfile6=infile.replace(".tif","_6km.tif")
		outfile10=infile.replace(".tif","_10km.tif")
		re_griding(infile,constant.res3x,constant.res3y,outfile3)
		re_griding(infile,constant.res6x,constant.res6y,outfile6)
		re_griding(infile,constant.res10x,constant.res10y,outfile10)
if __name__ == '__main__':
	#main()
	regrid_landcover()